import axios, { type AxiosInstance } from 'axios'

const request: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL || '/api',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
})

request.interceptors.request.use(
    (config: any) => {
        config.headers = config.headers || {}
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    },
)

request.interceptors.response.use(
    (response) => {
        const code:number = response.data.code
        if (code !== 200) {
            return Promise.reject(response.data)
        }
        return response.data
    },
    (error) => {
        return Promise.reject(error)
    },
)

export default request
